<script lang="ts" setup generic="T extends ExexecuteList">
import { Button, Modal, Table, Tooltip } from 'ant-design-vue'
import { type AfterFetchContext, objectOmit } from '@vueuse/core'
import { LoadingOutlined } from '@ant-design/icons-vue'
import type { IBasic } from '~/types/apis/basic'
import type {
  ExexecuteList,
  IExexute,
  IExexuteList,
} from '~/types/apis/execute'
import type { ColumnsType } from 'ant-design-vue/es/table'
import { ref, computed, reactive } from 'vue'
import { watchImmediate } from '@vueuse/core'
import { useGlobalConfigStore } from '../../stores/global-config.store'
import { useCustomFetch } from '../../composables/custom-fetch'
import { debug } from 'console'



const globalConfigStore = useGlobalConfigStore()
const { baseName, expandColumnsBefore, expandColumnsAfter } = withDefaults(
  defineProps<{
    baseName: string
    expandColumnsAfter?: ColumnsType<any>
    expandColumnsBefore?: ColumnsType<any>
  }>(),
  {
    expandColumnsAfter: () => [],
    expandColumnsBefore: () => [],
  },
)
const executeId = defineModel<number>('executeId', { required: true })
const visibleModel = defineModel<boolean>('visibleModel', { required: true })
const stepIdList = defineModel<number[]>('stepIdList', { required: true })

let random = ref(Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000);
// 查询redis的起始下标(目的是增量查询redis，而不是全量，避免step巨多导致每次返回全量卡死)
let redisSelectStartIndex = ref(0);
const executeUrl = computed(
  () => `/engine-service/api/v1/${baseName}_case/execute?id=${executeId.value}&environmentId=${globalConfigStore.config.environmentId}&random=${random.value}&stepIdList=${stepIdList.value ?? []}`
)

// {
//     if(stepIdList){
//       `/engine-service/api/v1/${baseName}_case/execute?id=${executeId.value}&environmentId=${globalConfigStore.config.environmentId}&random=${random.value}&stepIdList=${stepIdList}`
//     }else{
//       `/engine-service/api/v1/${baseName}_case/execute?id=${executeId.value}&environmentId=${globalConfigStore.config.environmentId}&random=${random.value}`
//     }
//   }

const {
  data: executeInfo,
  execute: fetchGetExecuteInfo,
  isFetching: loadingWithFetchExexuteInfo,
} = useCustomFetch<IExexute<T>>(executeUrl, {
  immediate: false,
  initialData: [],
  afterFetch(ctx: AfterFetchContext<IBasic<IExexute<T>>>) {
    if (ctx.data && ctx.data.code === 0) {
      return {
        data: ctx.data.data,
        response: ctx.response,
      }
    }
    return ctx
  },
})


const getReportDetailFromRedisUrl = computed(
  () => `/data-service/api/v1/report_detail/realTimeReportDetail?random=${random.value}&startIndex=${redisSelectStartIndex.value}`,
)


/**
 * 实时获取redi生中保存的临时报告详情
 */
const {
  data: currentReportDetail,
  execute: fetchGetReportDetailFromRedis,
  isFetching: loadingWithFetchReportDetailFromRedis,
} = useCustomFetch<IExexute<T>>(getReportDetailFromRedisUrl, {
  immediate: false,
  initialData: [],
  afterFetch(ctx: AfterFetchContext) {

    if (ctx.data && ctx.data.code === 0) {
      let resultArr: any = ref([])
      // 遍历数组
      const detailArrs: [] = ctx.data.data;
      detailArrs.map(item => {
        const processedItem = {
          ...objectOmit(item, ['step']),
        };
        // resultArr.value.push(processedItem)
        dataSource.value.push(processedItem)
      })
      console.info("dataSource条数: " + dataSource.value.length + ", redisSelectStartIndex.value: " + redisSelectStartIndex.value)
      if (dataSource.value !== null && dataSource.value !== undefined) {
        redisSelectStartIndex.value = dataSource.value.length
      }


      // dataSource.value = resultArr.value;

      return {
        data: ctx.data.data,
        response: ctx.response,
      }
    }
    return ctx
  },
})


const deleteRedisReportDetail = computed(
  () => `/data-service/api/v1/report_detail/delReportDetail?random=${random.value}`,
)

/**
 * 删除redis中暂存的reportDetail详情内容
 */
const {
  execute: fetchGetDeleteReportRedis,
  isFetching: loadingWithFetchDeleteRedisReportDetail,
} = useCustomFetch<IExexute<T>>(deleteRedisReportDetail, {
  immediate: false,
  initialData: [],
  afterFetch(ctx: AfterFetchContext) {
    return ctx
  },
})


const modalDetails = reactive({
  title: '',
  content: '',
  visible: false,
})

const columns = ref<ColumnsType<any>>([
  {
    key: 'executeState',
    dataIndex: 'executeState',
    title: '执行结果',
    align: 'center',
    width: 100,
  },
  ...expandColumnsBefore,
  {
    key: 'assertionState',
    dataIndex: 'assertionState',
    title: '断言结果',
    align: 'center',
    width: 100,
  },
  {
    key: 'exceptionMsg',
    dataIndex: 'exceptionMsg',
    title: '异常信息',
    align: 'center',
    width: 100,
  },
  {
    key: 'expendTime',
    dataIndex: 'expendTime',
    title: '耗时',
    align: 'center',
    width: 80,
  },
  ...expandColumnsAfter,
])


// const dataSource = computed<(Omit<IExexuteList<T>, 'step'> & T)[]>(() => {
//   if (!executeInfo.value?.list || executeInfo.value.list.length <= 0) return []

//   const list = executeInfo.value.list

//   return list.map((item) => ({
//     ...objectOmit(item, ['step']),
//     ...item.step,
//   }))
// })

let dataSource: any = ref([]);
let socket: any = undefined; // 在这里声明 socket 变量
let timerId: any = null;

watchImmediate(executeId, () => {
  if (executeId.value !== -1) {
    console.info("开始执行engine")
    // 清空redis起始Index, 以及dataSource
    redisSelectStartIndex.value = 0
    dataSource.value = []
    random.value = Math.floor(Math.random() * (999999 - 100000 + 1)) + 100000;

    fetchGetExecuteInfo()

    timerId = setInterval(() => {
      fetchGetReportDetailFromRedis()
    }, 500);

  }
})

/**
 * 关闭弹窗时触发(点击去详情报告不会触发该函数)
 */
watchImmediate(visibleModel, () => {
  console.info("visible状态: " + JSON.stringify(visibleModel.value))
  if (!visibleModel.value) {
    // 停止定时器，并删除redis中临时报告
    clearInterval(timerId);
    fetchGetDeleteReportRedis();
  }
})


/**
 * 点击去报告详情按钮时触发
 * @param data 关闭websocket
 */
function closeWebsocket(data: any) {
  console.info("子组件传来了数据")
  clearInterval(timerId);
  fetchGetDeleteReportRedis();

}


function handleModalCancel() {
  executeId.value = -1
  visibleModel.value = false
}

function setModalDetails(title: string, content: string) {
  modalDetails.title = title
  modalDetails.content = content
  modalDetails.visible = true
}

function handleModalDetailsCancel() {
  modalDetails.title = ''
  modalDetails.content = ''
  modalDetails.visible = false
}

defineExpose({
  setModalDetails,
})
</script>

<template>
  <div>
    <Modal v-model:open="modalDetails.visible" :title="modalDetails.title" width="50%" @ok="handleModalDetailsCancel"
      @cancel="handleModalDetailsCancel">
      <pre>{{ modalDetails.content }}</pre>
    </Modal>
    <Modal v-model:open="visibleModel" :footer="null" title="执行结果" width="70%" @cancel="handleModalCancel">
      <!-- <div
        v-if="loadingWithFetchExexuteInfo"
        flex="~ items-center justify-center"
        text="20"
      >
        <LoadingOutlined />
      </div> -->
      <div>
        <ExecuteResult :model-value="executeInfo" :base-name="baseName" @send-data="closeWebsocket" />

        <Table :pagination="false" :columns="columns" :data-source="dataSource" :scroll="{ x: 1000 }">
          <template #bodyCell="{ column, record, index, text, value }">
            <template v-if="['executeState', 'assertionState'].includes(
              column.key?.toString() ?? '',
            )
              ">
              <ExecuteState :model-value="record[column.key!]" />
            </template>

            <template v-else-if="column.key === 'exceptionMsg'">
              <span v-if="record[column.key!] == null">无</span>
              <div v-else>
                <Button type="primary" size="small" @click="
                  setModalDetails(
                    column.title as string,
                    record[column.key].toString(),
                  )
                  ">
                  查看详情
                </Button>
              </div>
            </template>

            <!-- 消耗时间 -->
            <template v-else-if="column.key === 'expendTime'">
              <div>{{ record[column.key!] ?? 0 }}ms</div>
            </template>

            <!-- 重试次数赋值 -->
            <template v-else-if="column.key === 'alreadyRetriesCount'">
              <div>{{ record[column.key!] ?? 0 }}次</div>
            </template>

            <!-- api, ui ,mix3个部分的执行弹窗内容 -->
            <template
              v-else-if="baseName === 'api' && (column.key === 'name' || column.key === 'path' || column.key === 'description')">
              <Tooltip color="#999" :title="record['apiCaseStep'][column.key]">
                <span>{{ record['apiCaseStep'][column.key] ?? '-' }}</span>
              </Tooltip>

            </template>
            <template
              v-else-if="baseName === 'ui' && (column.key === 'name' || column.key === 'locationType' || column.key === 'locationExpress' || column.key === 'value' || column.key === 'description')">
              <Tooltip color="#999" :title="record['uiCaseStep'][column.key]">
                <span>{{ record['uiCaseStep'][column.key] ?? '-' }}</span>
              </Tooltip>
            </template>
            <template
              v-else-if="baseName === 'mix' && (column.key === 'name' || column.key === 'path' || column.key === 'description')">
              <Tooltip color="#999" :title="record['mixCaseStepDTO'][column.key]">
                <span>{{ record['mixCaseStepDTO'][column.key] ?? '-' }}</span>
              </Tooltip>

            </template>


            <template v-else-if="value">
              <p truncate>{{ value }}</p>
            </template>

            <template v-else-if="value == null || value === ''"> - </template>

            <slot name="bodyCell" :column="column" :record="record" :text="text" :index="index" :value="value" />
          </template>
        </Table>
      </div>
    </Modal>
  </div>
</template>
